
require 'Common/define'
require 'Logic/Config'
require 'Common/functions'
require 'Net/itemHandler'

UICharactorInfoHeroAttribute = {};
HelperFunc.SetUIEnv(UICharactorInfoHeroAttribute)
local this = UICharactorInfoHeroAttribute;

this.linkColor = "#"..G.dataTable["t_global"][tostring(185)]["f_string_value"];
this.normalColor ="#FFFFFF";
this._showMaxLevelNum = 5;
this._showMaxLevelInterval = 500;
this._concealMaxLevelInterval = 5000;
---@type FairyGUI.GComponent
this.gameObject = nil;
this.transform = nil;
this.LuaBehaviour = nil;

this.hasInit = false;

this.currentHeroData = nil;
this.charactorExpConfig = nil;
this.heroConfig = nil;
this.itemConfig = nil;

this.curCharatorExpConfig = nil;
this.nextCharatorExpConfig = nil;

this.txtLevel = nil;
this.txtAtk = nil;
this.txtDef = nil;
this.txtHp = nil;
this.btnDetails = nil;

this.txtUnLevel = nil; --无法继续升级的说明
---@type FairyGUI.Controller
this.ctrlObjLevelGroup = nil
this.ctrlObjBtnGrid = nil;
this.btnLevelUp = nil;
---@type FairyGUI.GList
this.objItemParent = nil;
this.objItems ={};

this.btnLink = nil; --智慧之链按钮
this.btnUnlick = nil; --智慧之链（解链）按钮
this.btnReborn = nil;
this.linkController = nil;
this.timerId = nil;
this.costIdList = {};
this.canFireClick=false
this.info={}
this.flag=-1
this.itemCtrl = nil
local ENU_LEV =
{
    OK = 0;
    MAX_LEV         = 1, --达到最大等级
    QUALITY_LIMIT   = 2, --达到当前品质（星级）的最大等级
    LINK_LIMIT      = 3, --智慧链限制
    EXP_LIMIT       = 4, --英雄经验限制
    ITEM_LIMIT      = 5, --资源限制（道具消耗）
    ITEM_MONEY      = 6, --金币限制
}

function UICharactorInfoHeroAttribute.Init(partnerId, closeFunc, isShowOneHero) --todo 应该小写 暂时先大写
    local name ,package = getUIName(PanelNames.UICharactorInfoHeroAttribute);
    currentHeroData = logicMgr.HeroManager.getHeroDatabyPartnerId(partnerId,true);
    this.goFunc = closeFunc;
    this.isShowOneHero = isShowOneHero;
    if charactorExpConfig ==nil then
        charactorExpConfig = G.dataTable["t_characterexp"];
    end
    if itemConfig == nil then
        itemConfig =  G.dataTable["t_item"]
    end
    if heroConfig == nil then
        heroConfig = G.dataTable["t_hero"]
    end
    panelMgr:ShowUI(name,package, this.onCreate,Config.useLocalUI);
end
---@param obj FairyGUI.GComponent
function UICharactorInfoHeroAttribute.onCreate(obj)
    gameObject = obj;
    if not hasInit then
        hasInit = true;
        txtLevel = obj:GetChild("number")
        txtAtk = obj:GetChild("fight"):GetChild("number")
        txtDef = obj:GetChild("fy"):GetChild("number")
        txtHp = obj:GetChild("life"):GetChild("number")
        btnDetails = obj:GetChild("informationButton")
        
        txtUnLevel = obj:GetChild("UnLevelTip")
        ctrlObjLevelGroup = obj:GetController("LevelUpObj")
        btnLevelUp =  obj:GetChild("lvlupButton")
        objItemParent =  obj:GetChild("Sv")
        ctrlObjBtnGrid = obj:GetController("ButtonGrid")
        linkController = obj:GetController("HeroLink")
        this.showSourceController = obj:GetController("showSource")
        this.maxLevelController = obj:GetController("MaxLevel")
        this.isShowOneController = obj:GetController("isShowOne")
        btnLink = obj:GetChild("linklButton")
        btnUnlick = obj:GetChild("unlinklButton")
        btnReborn = obj:GetChild("csButton")
        this.btnSource = obj:GetChild("btnSource")
        this.effectController = this.btnSource:GetController("effect")
        this.Btn_MaxLevel = obj:GetChild("Btn_MaxLevel")
        this.btnInherit = obj:GetChild("btnInherit")
        this.btnInherit.title = getLanguage("HeroLinkTips8")
        this.sourceUIobj = obj:GetChild("UISourceMultiple")
        itemCtrl = obj:GetController("BgPos")

        ctrlObjLevelGroup:SetSelectedIndex(1)
        ctrlObjBtnGrid:SetSelectedIndex(1)
        this.addEvent();
    end
    if this.isShowOneHero then
        btnLink.visible = false;
        this.isShowOneController.selectedIndex = 1;
    else
        btnLink.visible = true;
        this.isShowOneController.selectedIndex = 0;
    end
    this.isClickLevelUp = false
    this.isClickLink = false
    this.maxLevelController.selectedIndex = 0;
    this.levelUpNum = 0;
    this.isLevelUp = false;
    this.refresh();
end

function UICharactorInfoHeroAttribute.addEvent()
    btnDetails.onClick:Add(this.onClickDetails)
    --btnLevelUp.onClick:Add(this.onClickLevelUp)
    btnLevelUp.onTouchBegin:Add(this.OnTouchStart)
    btnLevelUp.onTouchEnd:Add(this.OnTouchUp)
    btnLink.onClick:Add(this.onClickLink)
    btnUnlick.onClick:Add(this.onClickUnlink)
    btnReborn.onClick:Add(this.onClickReborn)
    this.Btn_MaxLevel.onClick:Add(this.onClickMaxLevel)
    this.btnInherit.onClick:Add(this.onClickInherit)
    this.btnSource.onClick:Add(this.onClickSource)
    logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UICharactorInfoHeroAttribute,Config.FuncOpenType.HeroReborn, btnReborn.name,btnReborn);
    logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UICharactorInfoHeroAttribute,Config.FuncOpenType.HeroLink, btnLink.name,btnLink);
    logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UICharactorInfoHeroAttribute,Config.FuncOpenType.HeroLink, "btnInherit", this.btnInherit);
end

function UICharactorInfoHeroAttribute.removeEvent()
    btnDetails.onClick:Remove(this.onClickDetails)
    --btnLevelUp.onClick:Remove(this.onClickLevelUp)
    btnLink.onClick:Remove(this.onClickLink)
    btnUnlick.onClick:Remove(this.onClickUnlink)
    btnReborn.onClick:Remove(this.onClickReborn)
    btnLevelUp.onTouchBegin:Remove(this.OnTouchStart)
    btnLevelUp.onTouchEnd:Remove(this.OnTouchUp)
    this.Btn_MaxLevel.onClick:Remove(this.onClickMaxLevel)
    this.btnInherit.onClick:Remove(this.onClickInherit)
    logicMgr.FuncOpenManager.removeStatusCtr(PanelNames.UICharactorInfoHeroAttribute);
end

function UICharactorInfoHeroAttribute.LocalListenEvent()
    ListenEvent(Config.EventType.QuickBattle ,this.reGetData);
    ListenEvent(Config.EventType.Fresh_Level,this.RefreshLevelByMsg);
    ListenEvent(Config.EventType.Fresh_Star,this.reGetData);
    ListenEvent(Config.EventType.Fresh_Skill,this.reGetData);
    ListenEvent(Config.EventType.Fresh_Mercenary,this.reGetData);
    ListenEvent(Config.EventType.Fresh_HeroLink,this.FreshHeroLink);
    ListenEvent(Config.EventType.Reset_Weapon,this.reGetData);
    ListenEvent(Config.EventType.Update_Weapon,this.reGetData);
    ListenEvent(Config.EventType.Update_WeaponAttrId,this.reGetData);
    --ListenEvent(Config.EventType.Fresh_Currency,this.reGetData);
    ListenEvent(Config.EventType.Fresh_Bag,this.updateSource);
    ListenEvent(Config.EventType.Fresh_BagUseItemBack, logicMgr.ItemManager.showGetItem);
    ListenEvent(Config.EventType.Fresh_BagUseItemBack, this.RefreshHeroInfo);
    ListenEvent(Config.EventType.GuideLevelUpStop,this.GuideLevelUpStop)
    --ListenEvent(Config.EventType.ShowHeroLvUpResult,this.ShowResult);
    ListenEvent(Config.EventType.FastConsumption,this.FastConsumption);
end

function UICharactorInfoHeroAttribute.LocalCloseEvent()
    CloseEvent(Config.EventType.QuickBattle,this.reGetData);
    CloseEvent(Config.EventType.Fresh_Level,this.RefreshLevelByMsg);
    CloseEvent(Config.EventType.Fresh_Star,this.reGetData);
    CloseEvent(Config.EventType.Fresh_Skill,this.reGetData);
    CloseEvent(Config.EventType.Fresh_Mercenary,this.reGetData);
    CloseEvent(Config.EventType.Fresh_HeroLink,this.FreshHeroLink);
    CloseEvent(Config.EventType.Reset_Weapon,this.reGetData);
    CloseEvent(Config.EventType.Update_Weapon,this.reGetData);
    CloseEvent(Config.EventType.Update_WeaponAttrId,this.reGetData);
    --CloseEvent(Config.EventType.Fresh_Currency,this.reGetData);
    CloseEvent(Config.EventType.Fresh_Bag,this.updateSource);
    CloseEvent(Config.EventType.Fresh_BagUseItemBack, logicMgr.ItemManager.showGetItem);
    CloseEvent(Config.EventType.Fresh_BagUseItemBack, this.RefreshHeroInfo);
    CloseEvent(Config.EventType.GuideLevelUpStop,this.GuideLevelUpStop)
    --CloseEvent(Config.EventType.ShowHeroLvUpResult, this.ShowResult);
    CloseEvent(Config.EventType.FastConsumption,this.FastConsumption);

end
function UICharactorInfoHeroAttribute.FreshHeroLink()
    if this.isClickLink then
        this.reGetData()
    end
end
function UICharactorInfoHeroAttribute.ShowResult()
    if(this.flag<0)then
        return
    end
    this.data={}
    this.data.flag=this.flag
    this.data.partnerId=currentHeroData.partnerId
    this.data.skillType=this.skillType
    this.data.beforePower=this.beforePower
    this.flag=-1
    showUI(PanelNames.UICharactorInfoUpgradeResult,this.data)
end
function UICharactorInfoHeroAttribute.SkillUpConfirmCallBack(flag,type,beforePower)
    this.flag=flag
    this.skillType=type
    this.beforePower=beforePower
end
function UICharactorInfoHeroAttribute.OnDestroy()
    this.removeEvent();
    this.removeLevelUpTimer()
    hasInit = false
end

function UICharactorInfoHeroAttribute.OnEnable()
    this.LocalListenEvent();
end

function UICharactorInfoHeroAttribute.removeLevelUpTimer()
    if this.timerId ~= nil then
        utimer.remove(this.timerId)
        this.timerId = nil
    end
    utimer.remove(this.longPressTickId)
    this.longPressTickId = nil
end

function UICharactorInfoHeroAttribute.OnDisable()
    AudioManager.IsHeroLevelUp = false
    this.LocalCloseEvent();
    this.removeLevelUpTimer()
    if this.maxLevelShowTime ~= nil then
        utimer.remove(this.maxLevelShowTime);
    end
    if this.maxLevelConcealTime ~= nil then
        utimer.remove(this.maxLevelConcealTime);
    end
    hasInit = false;
end

function UICharactorInfoHeroAttribute.reGetData()
    if currentHeroData~=nil then
        currentHeroData = logicMgr.HeroManager.getHeroDatabyPartnerId(tostring(currentHeroData["partnerId"]),true)
        this.refresh()
    end
end
function UICharactorInfoHeroAttribute.RefreshLevelByMsg()
    this.isWaitingLevelUpMsg = nil
    this.reGetData()
    if not logicMgr.GuideMgr.IsGuiding() and  this.currentHeroData.level == this.GetMaxLevel() then
        utimer.delayCall(function()
            local flag = this.CheckCanLevUp(this.currentHeroData.level, false)
            if flag ~= ENU_LEV.MAX_LEV and flag ~= ENU_LEV.QUALITY_LIMIT and flag ~= ENU_LEV.LINK_LIMIT  then
                this.updateSourceData(this.needCostList);
            end
            this.LevelUp(nil)
        end,1)
    end
    FireEvent(Config.EventType.GuideLevelUp,this.levelUpStateOk == ENU_LEV.OK,currentHeroData.level)
end
function UICharactorInfoHeroAttribute.refresh()
    if currentHeroData==nil or charactorExpConfig==nil then
        logError("配置为空，或英雄信息为空");
        return;
    end
    curCharatorExpConfig = charactorExpConfig[MakeTopLevelId(currentHeroData["level"])]
    if curCharatorExpConfig ==nil then
        logError(string.format("未找到id为%d的配置",currentHeroData["level"]));
        return;
    end
    nextCharatorExpConfig = charactorExpConfig[MakeTopLevelId(currentHeroData["level"]+1)];
    local attrData;
    if not linkController then
        linkController = gameObject:GetController("HeroLink")
    end
    local level, isInLink = logicMgr.HeroManager.getHeroShowLevelByPartnerId(currentHeroData.partnerId);
    if isInLink == 2 then
        linkController:SetSelectedIndex(2);
        txtLevel.text = string.TextColor(level, logicMgr.HeroManager.lvColors[2]);
        -- 用连接英雄等级计算基础属性
        logicMgr.HeroManager.processHeroBaseAttr(currentHeroData,level,currentHeroData["star"],true)
        -- 刷新总属性
        logicMgr.HeroManager.processHeroAllAttr(currentHeroData);
        attrData =  currentHeroData["totalAttribute"];
    else
        linkController:SetSelectedIndex(0);
        txtLevel.text = string.TextColor(level,normalColor);
        logicMgr.HeroManager.processHeroBaseAttr(currentHeroData,level,currentHeroData["star"],true)
        -- 刷新总属性
        logicMgr.HeroManager.processHeroAllAttr(currentHeroData);
        attrData =  currentHeroData["totalAttribute"];
    end
    txtAtk.text = Mathf.Round(attrData[EnumConst.FighterAttributeEnum.ATK]);
    txtDef.text = Mathf.Round(attrData[EnumConst.FighterAttributeEnum.DEF]);
    txtHp.text = Mathf.Round(attrData[EnumConst.FighterAttributeEnum.HP]);
    this.RefreshHeroInfo();
    if this.maxLevel ~= nil and this.maxLevel <= currentHeroData.level then
        this.maxLevelController.selectedIndex = 0;
    end
end

function UICharactorInfoHeroAttribute.RefreshHeroInfo()
    --objHeroGroup:SetActive(true);
    this.levelUpStateOk = ENU_LEV.OK
    ctrlObjBtnGrid:SetSelectedIndex(1)
    ctrlObjLevelGroup:SetSelectedIndex(1)
    objItemParent.visible = true
    btnLevelUp.touchable = true;

    local isInLink = logicMgr.HeroLinkManager.isInLink(currentHeroData.partnerId,false);
    this.effectController.selectedIndex = 0;
    --if nextCharatorExpConfig ==nil then --最高等级
    --if logicMgr.HeroLinkManager.IsTopLevelOpen() then
    --    this.btnInherit.visible = false;
    --end
    if logicMgr.HeroManager.IsMaxLevel(currentHeroData.level) then
        if HeroLinkManager.isMainHero(currentHeroData.partnerId) and HeroLinkManager.IsTopLevelOpen() then
            txtUnLevel.visible = true
            txtUnLevel.text = getLanguage("Character_Tips4")
            ctrlObjLevelGroup:SetSelectedIndex(0)
            btnLevelUp.touchable = false;
        else
            txtUnLevel.visible = true;
            txtUnLevel.text = getLanguage("Sys_MsgMaxLevel");
            ctrlObjLevelGroup:SetSelectedIndex(0)
            btnLevelUp.touchable = false;
        end
    elseif isInLink then
        txtUnLevel.visible = true
        txtUnLevel.text = getLanguage("Character_Tips4")
        ctrlObjLevelGroup:SetSelectedIndex(0)
        btnLevelUp.touchable = false;
    else
        local showText = false
        local enu, txtContent = this.CheckCanLevUp(currentHeroData.level, false)
        this.levelUpStateOk = enu
        if enu == ENU_LEV.QUALITY_LIMIT or enu == ENU_LEV.LINK_LIMIT then
            showText = true
        end
        txtUnLevel.visible = showText
        btnLevelUp.touchable = not showText
        if txtContent ~= nil then
            ctrlObjLevelGroup:SetSelectedIndex(0)
            txtUnLevel.text = txtContent
        end
        local costs = clone(curCharatorExpConfig["f_HeroCost"]);
        local expTable = {CurrencyEnum.HeroExp,curCharatorExpConfig["f_HeroExp"]};
        table.insert(costs,expTable);
        local index =0;
        objItemParent:RemoveChildrenToPool()
        this.costIdList = {};
        this.needCostList = {};
        this.info={}
        if #costs== 3 then
            itemCtrl.selectedIndex = 1
        else
            itemCtrl.selectedIndex = 0
        end
        for k ,v in pairs(costs) do
            index = index+1;
            local costId = v[1];
            local costNum =v[2];
            local hasNum = 0;
            local itemType = logicMgr.ItemManager.getItemTabType(costId);
            ---@type FairyGUI.GComponent
            local item = objItemParent:AddItemFromPool()
            local txt = item:GetChild("ItemText")
            local imgItem = item:GetChild("ItemIcon")
            local btnJump = item:GetChild("btnJump")
            if itemType == EnumConst.ItemTableEnum.Currency then
                hasNum = logicMgr.ItemManager.getCurrencyCountByModelId(costId);
            else
                hasNum = logicMgr.ItemManager.getItemCountbyModelId(tostring(costId));
            end
            if hasNum>=costNum then
                txt.text = table.concat({ getNumString(hasNum), "/", getNumString(costNum)})
            else
                table.insert(this.needCostList, costId);
                if not logicMgr.ItemManager.getSourceStart("UICharactorInfoHeroAttribute") then
                    this.effectController.selectedIndex = 1;
                end
                local str = getNumString(costNum);
                txt.text = table.concat({string.TextColor(getNumString(hasNum),"#FF0000"), "/", str})
            end

            local curItemConfig = itemConfig[tostring(costId)];
            local url="ui://ItemAtlas/"..curItemConfig.f_Icon
            if imgItem~=nil and curItemConfig~=nil then
                imgItem.url = url
            end
            table.insert(this.info,{txt.text,url})
            btnJump.onClick:Clear();
            btnJump.onClick:Add(function ()
                this.updateSourceData({this.costIdList[k]});
            end);
            this.costIdList[k] = costId;
        end
    end

    local rebornFag = currentHeroData["level"] > 1 ;
    if logicMgr.HeroLinkManager.isMainHero(currentHeroData.partnerId) then
        btnLink.visible = false;
        btnUnlick.visible = false;
        if HeroLinkManager.IsTopLevelOpen() then
            rebornFag = false
        end
    else
        btnUnlick.visible = true
        btnLink.visible = true
        local typeId, grayId, lockId,hideId = logicMgr.FuncOpenManager.checkStatus(Config.FuncOpenType.HeroLink);
        if isInLink then
            logicMgr.FuncOpenManager.setGameObjectStatus(typeId, grayId, lockId,hideId,btnUnlick);
            btnLink.visible = false;
        else
            logicMgr.FuncOpenManager.setGameObjectStatus(typeId, grayId, lockId,hideId,btnLink);
            btnUnlick.visible = false;
        end
    end

    if rebornFag then
        local typeId, grayId, lockId ,hideId= FuncOpenManager.checkStatus(Config.FuncOpenType.HeroReborn);
        FuncOpenManager.setGameObjectStatus(typeId, grayId, lockId,hideId,btnReborn);
    else
        btnReborn.visible = false;
    end
end

function UICharactorInfoHeroAttribute.onClickDetails()
    showUI(PanelNames.UICharactorAttributeDetails,currentHeroData);
end

function UICharactorInfoHeroAttribute.OnTouchStart()
    if this.isWaitingLevelUpMsg then
        return
    end
    this.sendMsg = nil
    this.isClickLevelUp = true
    this.isClickLink = false 
    this.curLevel = currentHeroData.level
    this.curData = {}
    this.removeLevelUpTimer()
    this.timerId = utimer.delayCall(this.LongPress,500)
end
function UICharactorInfoHeroAttribute.LongPress()
    if this.longPressTickId then return end
    this.longPressTickId = utimer.timeCall(this.LongPressTick,100,-1)
end
function UICharactorInfoHeroAttribute.LongPressTick()
    if this.isLevelUp then
        return;
    end
    this.isLevelUp = true;
    if this.curLevel == this.GetMaxLevel() then
        this.removeLevelUpTimer()
        this.sendMsg = true
        local dis_level = this.curLevel - currentHeroData.level
        if dis_level > 0 then
            this.sendUpLevelMessage(dis_level)
        else
            this.LevelUp(nil)
        end
        this.maxLevelController.selectedIndex = 0
        this.isLevelUp = false;
    else
        this.LevelUp(this.curData)
    end
end
function UICharactorInfoHeroAttribute.OnTouchUp()
    this.isLevelUp = true;
    if not this.curLevel then
        this.isLevelUp = false;
        return
    end
    this.removeLevelUpTimer()
    this.isLevelUp = false;
    if not this.sendMsg then
        this.LevelUp(nil)
        if not this.curLevel then return end
        local dis_level = this.curLevel - currentHeroData.level
        if dis_level > 0 then
            this.sendUpLevelMessage(dis_level)
        end
    end
    this.curLevel = nil
end
function UICharactorInfoHeroAttribute.sendUpLevelMessage(level)
    this.isWaitingLevelUpMsg = true
    partnerHandler.sendUpLevelMessage(currentHeroData.partnerId, level)
    utimer.delayCall(this.EnableWaitingLevelUp,500)
end
function UICharactorInfoHeroAttribute.EnableWaitingLevelUp()
    this.isWaitingLevelUpMsg = nil
end
function UICharactorInfoHeroAttribute.ShowConfirm()
    this.resultData={}
    this.resultData.info=this.info
    this.resultData.partnerId=currentHeroData.partnerId
    showUI(PanelNames.UISkillLevelUp,this.resultData,this.LevelUpCallBack)
end

function UICharactorInfoHeroAttribute.onClickLevelUp()
    this.removeLevelUpTimer()
    this.LevelUp(nil);
end

function UICharactorInfoHeroAttribute.LevelUpCallBack(flag,type,beforePower)
    this.SkillUpConfirmCallBack(flag,type,beforePower)
    this.LevelUp(nil) 
end

function UICharactorInfoHeroAttribute.LevelUp(data)
    if this.curLevel == nil then
        this.isLevelUp = false;
        return
    end
    local flag = 0;
    if data ~= nil then
        flag = this.CheckCanLevUp(this.curLevel, false, data)
    else
        flag = this.CheckCanLevUp(currentHeroData.level, true)
    end
    if flag == ENU_LEV.OK then
        --英雄升级
        AudioManager.PlayInteractionVoice(this.currentHeroData["partnerModelId"], 0, AudioManager.InteractionTagTable[10].Tag)
        AudioManager.Play(2001)
        this.curLevel = this.curLevel + 1
        txtLevel.text = this.curLevel
        --partnerHandler.sendUpLevelMessage(currentHeroData.partnerId)
        if logicMgr.MapManager.getMapId() >= G.dataTable["t_global"][tostring(233)].f_int_value then
            this.levelUpNum = this.levelUpNum + 1;
            if this.levelUpNum >= this._showMaxLevelNum then
                if this.maxLevelController.selectedIndex == 0 then
                    this.showMaxLevel()
                end
            end
            if this.maxLevelShowTime ~= nil then
                utimer.remove(this.maxLevelShowTime);
            end
            this.maxLevelShowTime = utimer.timeCall(function()
                this.levelUpNum = 0;
                this.maxLevelShowTime = nil;
            end, this._showMaxLevelInterval, 1);
            if this.maxLevelConcealTime ~= nil then
                utimer.remove(this.maxLevelConcealTime);
            end
            this.maxLevelConcealTime = utimer.timeCall(function()
                this.maxLevelController.selectedIndex = 0;
                this.maxLevelConcealTime = nil;
            end, this._concealMaxLevelInterval, 1);
        end
    elseif flag == ENU_LEV.EXP_LIMIT or flag == ENU_LEV.ITEM_LIMIT or flag == ENU_LEV.ITEM_MONEY then
        if not logicMgr.GuideMgr.IsGuiding() and data == nil then
            this.updateSourceData(this.needCostList);
        end
    end
    if flag ~= ENU_LEV.OK then
        if data ~= nil then
            this.maxLevelController.selectedIndex = 0
        end
        FireEvent(Config.EventType.GuideLevelUp, false)
        local mgr = logicMgr.GuideMgr
        if not mgr.IsGuiding() then
            if flag == ENU_LEV.EXP_LIMIT then
                mgr.AddTrigger(mgr.TriggerType.expToExpedition, nil, nil, nil, true)
            elseif flag == ENU_LEV.ITEM_LIMIT then
                mgr.AddTrigger(mgr.TriggerType.stoneToTower, nil, nil, nil, true)
            end
        end
    else
        FireEvent(Config.EventType.GuideLevelUp, true, this.curLevel)
    end
    this.isLevelUp = false;
end

function UICharactorInfoHeroAttribute.onClickMaxLevel()
    this.sendUpLevelMessage( this.maxLevel - currentHeroData.level);
    this.maxLevelController.selectedIndex = 0;
    --英雄升级
    AudioManager.PlayInteractionVoice(this.currentHeroData["partnerModelId"],0,AudioManager.InteractionTagTable[10].Tag)
    AudioManager.Play(2001)
    --local flag,type=CheckHeroSkillUpgrade(currentHeroData.partnerId)
    --this.data.flag  =flag
    --showUI(PanelNames.UICharactorInfoUpgradeResult,this.data)
end

---智慧之链
function UICharactorInfoHeroAttribute.onClickInherit()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HeroLink, true, this.btnInherit) then
        this.isClickLink = true
        showUI(PanelNames.UIHeroLink, nil, nil, this.currentHeroData.partnerId);
    end
end

function UICharactorInfoHeroAttribute.GetMaxLevel()
    local level = currentHeroData.level - 1;
    local flag = 0;
    local data = {};
    while(flag) do
        level = level + 1;
        local flag1=this.CheckCanLevUp(level, false, data)==0
        --local flag2=CheckHeroSkillUpgrade(currentHeroData.partnerId,level)<0
        flag=flag1
    end
    return level
end

function UICharactorInfoHeroAttribute.showMaxLevel()
    local level = currentHeroData.level - 1;
    local flag = 0;
    local data = {};
    while(flag) do
        level = level + 1;
        local flag1=this.CheckCanLevUp(level, false, data)==0
        --local flag2=CheckHeroSkillUpgrade(currentHeroData.partnerId,level)<0
        flag=flag1
    end
    if level > currentHeroData.level then
        this.maxLevelController.selectedIndex = 1;
        this.maxLevel = level;
        this.Btn_MaxLevel.title = string.format(getLanguage("OneClickLevelUp", nil, "%d"), level);
    else
        this.maxLevelController.selectedIndex = 0;
        this.maxLevel = 0;
    end
end

--- 检测是否满足升级条件
function UICharactorInfoHeroAttribute.CheckCanLevUp(curHeroLev, shopTips, items)
    --达到最大等级
    if curHeroLev >= logicMgr.HeroManager.GetLimitLevel() then
        if shopTips then
            UISysTips.AddMsg(getLanguage("Sys_MsgMaxLevel"))
        end
        return ENU_LEV.MAX_LEV
    end
    --品质（星级）限制
    local cfgID = toNumber(currentHeroData["partnerModelId"]) * 1000 + currentHeroData["star"]
    local cfgInfo = dataTable.getRow("t_herorank", cfgID)
    if curHeroLev >= cfgInfo["f_LevelCap"] then
        local limitLev = cfgInfo["f_HeroStar"]
        for i = currentHeroData["star"], 150, 10 do
            cfgID = toNumber(currentHeroData["partnerModelId"]) * 1000 + i;
            cfgInfo = dataTable.getRow("t_herorank", cfgID)
            if cfgInfo ~= nil then
                if cfgInfo.f_LevelCap > curHeroLev then
                    limitLev = cfgInfo.f_HeroStar;
                    break;
                end
            end
        end
        local content = string.format(getLanguage("Character_Tips5"), EnumConst.StarType[logicMgr.HeroManager.starToQuality(limitLev)])
        if shopTips then
            UISysTips.AddMsg(content)
        end
        return ENU_LEV.QUALITY_LIMIT, content
    end
    --智慧链限制
    local levCfg = dataTable.getRow("t_characterexp", MakeTopLevelId(curHeroLev))
    if levCfg and levCfg["f_LevelupRequirement"] and levCfg["f_LevelupRequirement"] > 0 then
        local limitLev = levCfg["f_LevelupRequirement"]
        if logicMgr.HeroLinkManager.GetHeroLevel() < limitLev then
            local content = string.format(getLanguage("Character_Tips6"), limitLev)
            if shopTips then
                UISysTips.AddMsg(content)
            end
            return ENU_LEV.LINK_LIMIT, content
        end
    end
    local data = charactorExpConfig[MakeTopLevelId(curHeroLev)];
    --英雄经验限制
    if data == nil then
        logError(string.format("未找到id为%d的配置", curHeroLev));
        return ENU_LEV.EXP_LIMIT;
    end
    --资源限制（道具消耗）
    local costs = decodeJsonStrToTabel(data["f_HeroCost"]);
    for i = 1, #costs do
        local item = costs[i];
        local costId = item[1];
        local costNum = item[2];
        local itemType = logicMgr.ItemManager.getItemTabType(costId);
        local hasNum = 0;
        if itemType == EnumConst.ItemTableEnum.Currency then
            hasNum = logicMgr.ItemManager.getCurrencyCountByModelId(costId);
        else
            hasNum = logicMgr.ItemManager.getItemCountbyModelId(tostring(costId));
        end
        if items ~= nil then
            if items[costId] == nil then
                items[costId] = hasNum;
            else
                hasNum = items[costId];
            end
        end
        if costNum > hasNum then
            if shopTips then
                UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"),getLanguage(G.dataTable["t_item"][tostring(costId)].f_ItemName)))
            end
            if costId == CurrencyEnum.MONEY then
                return ENU_LEV.ITEM_MONEY
            else
                return ENU_LEV.ITEM_LIMIT
            end

        else
            if items ~= nil then
                items[costId] = items[costId] - costNum;
            end
        end
    end
    --英雄经验限制
    local costExp = data["f_HeroExp"];
    local hasExp = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.HeroExp);
    if items ~= nil then
        if items[CurrencyEnum.HeroExp] == nil then
            items[CurrencyEnum.HeroExp] = hasExp;
        else
            hasExp = items[CurrencyEnum.HeroExp];
        end
    end
    if costExp > hasExp  then
        if shopTips then
            UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"),getLanguage(G.dataTable["t_item"][tostring(CurrencyEnum.HeroExp)].f_ItemName)));
        end
        return ENU_LEV.EXP_LIMIT
    else
        if items ~= nil then
            items[CurrencyEnum.HeroExp] = items[CurrencyEnum.HeroExp] - costExp;
        end
    end
    return ENU_LEV.OK
end

function UICharactorInfoHeroAttribute.onClickLink()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HeroLink,true,btnLink) then
        this.isClickLevelUp = false
        this.isClickLink = true
        if this.goFunc then
            this.goFunc(PanelNames.UIHeroLink);
        end
        --showUI(PanelNames.UIHeroLink);
    end
end

function UICharactorInfoHeroAttribute.onClickUnlink()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HeroLink,true,btnUnlick) then
        this.isClickLevelUp = false
        this.isClickLink = true
        if this.goFunc then
            this.goFunc(PanelNames.UIHeroLink);
        end
        --showUI(PanelNames.UIHeroLink);
    end
end

function UICharactorInfoHeroAttribute.onClickReborn()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.HeroReborn,true,btnReborn) then
        showUI(PanelNames.UICharactorReborn,currentHeroData,0);
    end
end

function UICharactorInfoHeroAttribute.onClickSource()
    this.updateSourceData(this.costIdList);
end


function UICharactorInfoHeroAttribute.updateSourceData(data)
    if data == nil or #data <= 0 or this.isShowOneHero then
        return ;
    end
    this.showSourceController.selectedIndex = 1;
    this.showSourceList = data
    logicMgr.ItemManager.setSourceStart("UICharactorInfoHeroAttribute", true)
    this.effectController.selectedIndex = 0;
    this.updateSource();
end

function UICharactorInfoHeroAttribute.updateSource()
    if this.showSourceList == nil or #this.showSourceList <= 0 then
        return ;
    end
    logicMgr.ItemManager.updateSourceUI(this.sourceUIobj, this.showSourceList, function ()
        this.showSourceController.selectedIndex = 0;
    end, function ()
        this.showSourceController.selectedIndex = 0;
        if this.goFunc then
            this.goFunc();
        end
    end );
end
--引导升到指定等级后停止
function UICharactorInfoHeroAttribute.GuideLevelUpStop()
    if not this.curLevel then return end
    this.removeLevelUpTimer()
    if not this.sendMsg then
        local dis_level = this.curLevel - currentHeroData.level
        if dis_level > 0 then
            this.sendUpLevelMessage(dis_level)
        end
    end
    this.curLevel = nil
end

function UICharactorInfoHeroAttribute.FastConsumption(buyType)
    if buyType == 1 then
        this.RefreshHeroInfo();
    end
end

return UICharactorInfoHeroAttribute;
